"""
RagFlow 客户端 GUI 对话框模块
"""

from PySide6.QtCore import Qt
from PySide6.QtWidgets import (
    QDialog, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton,
    QTableWidget, QTableWidgetItem, QHeaderView, QTextEdit, QMessageBox
)

from ragflow_client.config import RagFlowConfig
from ragflow_client.service import RagFlowService


class SearchDialog(QDialog):
    """搜索对话框"""
    
    def __init__(self, parent, api_url, api_key, kb_id, debug=False):
        super().__init__(parent)
        self.api_url = api_url
        self.api_key = api_key
        self.kb_id = kb_id
        self.debug = debug
        
        self.setup_ui()
    
    def setup_ui(self):
        """创建界面"""
        self.setWindowTitle("搜索知识库")
        self.setMinimumSize(700, 500)
        
        # 创建布局
        layout = QVBoxLayout(self)
        
        # 创建搜索框
        search_layout = QHBoxLayout()
        layout.addLayout(search_layout)
        
        search_layout.addWidget(QLabel("搜索:"))
        self.search_edit = QLineEdit()
        search_layout.addWidget(self.search_edit)
        
        search_button = QPushButton("搜索")
        search_button.clicked.connect(self.do_search)
        search_layout.addWidget(search_button)
        
        # 创建结果显示区域
        self.result_text = QTextEdit()
        self.result_text.setReadOnly(True)
        layout.addWidget(self.result_text)
        
        # 创建关闭按钮
        close_button = QPushButton("关闭")
        close_button.clicked.connect(self.close)
        layout.addWidget(close_button)
    
    def do_search(self):
        """执行搜索"""
        query = self.search_edit.text().strip()
        if not query:
            QMessageBox.critical(self, "错误", "请输入搜索内容")
            return
        
        # 创建临时配置
        config = RagFlowConfig(
            api_url=self.api_url,
            api_key=self.api_key,
            kb_id=self.kb_id,
            kb_name="",
            parser_id="naive",
            doc_dir="",
            doc_suffix=[],
            debug=self.debug
        )
        
        # 创建服务
        service = RagFlowService(config)
        
        # 搜索
        try:
            status, results = service.search(query)
            if status:
                # 显示结果
                self.result_text.clear()
                if not results:
                    self.result_text.append("没有找到匹配的结果")
                    return
                
                for i, result in enumerate(results):
                    self.result_text.append(f"结果 {i+1}:")
                    self.result_text.append(f"相似度: {result.get('score', 0):.4f}")
                    self.result_text.append(f"内容: {result.get('content', '')}")
                    self.result_text.append(f"来源: {result.get('metadata', {}).get('source', '')}")
                    self.result_text.append("\n" + "-"*50 + "\n")
            else:
                QMessageBox.critical(self, "错误", f"搜索失败: {results}")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"搜索失败: {str(e)}")


class ChatDialog(QDialog):
    """对话对话框"""
    
    def __init__(self, parent, api_url, api_key, kb_id, debug=False):
        super().__init__(parent)
        self.api_url = api_url
        self.api_key = api_key
        self.kb_id = kb_id
        self.debug = debug
        self.history = []
        
        self.setup_ui()
    
    def setup_ui(self):
        """创建界面"""
        self.setWindowTitle("知识库对话")
        self.setMinimumSize(800, 600)
        
        # 创建布局
        layout = QVBoxLayout(self)
        
        # 创建对话历史显示区域
        self.chat_text = QTextEdit()
        self.chat_text.setReadOnly(True)
        layout.addWidget(self.chat_text)
        
        # 创建输入区域
        input_layout = QHBoxLayout()
        layout.addLayout(input_layout)
        
        self.input_edit = QTextEdit()
        self.input_edit.setMaximumHeight(100)
        input_layout.addWidget(self.input_edit)
        
        send_button = QPushButton("发送")
        send_button.setMinimumHeight(100)
        send_button.clicked.connect(self.send_message)
        input_layout.addWidget(send_button)
        
        # 创建关闭按钮
        close_button = QPushButton("关闭")
        close_button.clicked.connect(self.close)
        layout.addWidget(close_button)
    
    def send_message(self):
        """发送消息"""
        query = self.input_edit.toPlainText().strip()
        if not query:
            QMessageBox.critical(self, "错误", "请输入消息")
            return
        
        # 清空输入框
        self.input_edit.clear()
        
        # 显示用户消息
        self.chat_text.append(f"<b>用户:</b> {query}")
        
        # 创建临时配置
        config = RagFlowConfig(
            api_url=self.api_url,
            api_key=self.api_key,
            kb_id=self.kb_id,
            kb_name="",
            parser_id="naive",
            doc_dir="",
            doc_suffix=[],
            debug=self.debug
        )
        
        # 创建服务
        service = RagFlowService(config)
        
        # 对话
        try:
            status, result = service.chat(query, history=self.history)
            if status:
                # 显示回复
                answer = result.get("answer", "")
                self.chat_text.append(f"<b>助手:</b> {answer}")
                
                # 更新历史
                self.history.append({"role": "user", "content": query})
                self.history.append({"role": "assistant", "content": answer})
            else:
                self.chat_text.append(f"<b>错误:</b> {result}")
        except Exception as e:
            self.chat_text.append(f"<b>错误:</b> {str(e)}")